import config from '@/common/config.js';

import pinia from '@/store/index.js';
import { usePiniaStore } from '@/store/pinia.js';
const Pinia = usePiniaStore(pinia);

class Utils {
	Toast(title, state = 1, url, mask = true) {
		uni.showToast({
			title,
			mask,
			icon: 'none',
			success: () => {
				if (state == 2) {
					setTimeout(() => {
						uni.navigateBack({ delta: 1 })
					}, 800)
				} else if (state == 3) {
					setTimeout(() => {
						uni.redirectTo({ url })
					}, 800)
				}
			}

		})
	}


	showLoading(msg) {
		uni.showLoading({
			title: msg,
			mask: true,
		})
	}

	hideLoading() {
		uni.hideLoading();
	}

	imgUrls(imgs) {
		const reg = /^(http|https)/;
		if (!imgs) return;
		if (imgs.search(reg) != -1) return imgs;
		return config.imgUrl + imgs
	}

	staticImg(imgs) {
		return config.staticImg + imgs
	}

	pageHome() {
		uni.switchTab({
			url: '/pages/index/index'
		})
	}

	toUrl(url) {
		uni.navigateTo({
			url
		})
	}

	back(time) {
		uni.navigateBack({
			delta: time ? time : 1
		})
	}
	modelY(title, content = '', confirmText = "确定") {
		return new Promise((resolve, reject) => {
			uni.showModal({
				title,
				content,
				cancelColor: '#cccccc',
				confirmColor: Pinia.color,
				cancelText: '稍后完善',
				confirmText,
				success: (res) => {
					resolve(res.confirm)
				},

				fail: (err) => {
					reject(err)
				}
			})
		})
	}

	saveImage(path) {
		if (!path) return;
		uni.downloadFile({
			url: path,
			success: () => {
				const filePath = res.tempFilePath;
				uni.saveImageToPhotosAlbum({
					filePath,
					success: () => {
						this.Toast('保存成功')
					},
					fail: () => {
						this.Toast('保存失败')
					}
				})
			},
			fail: () => {
				this.Toast('保存失败')
			}

		})
	}

	setClip(text) {
		let that = this;
		if (!text) return;
		uni.setClipboardData({
			data: text,
			success: () => {
				this.Toast('复制成功')
			},
			fail: () => {
				this.Toast('复制失败')
			}

		})
	}

	BarTitle(title) {
		uni.setNavigationBarTitle({
			title
		})
	}

	pageTab(url) {
		uni.switchTab({
			url
		})
	}
}


export default new Utils();